package cn.xeblog.forward.handler;

import cn.xeblog.forward.codec.SharedMessageCodec;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author eleven
 * @date 2024/12/16 9:18
 * @apiNote
 */
@Slf4j
public class ForwardInitializer extends ChannelInitializer<NioSocketChannel> {
    @Override
    protected void initChannel(NioSocketChannel ch) throws Exception {
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        ch.pipeline()
                .addLast(loggingHandler)
                .addLast(new IdleStateHandler(30, 30, 30))
                .addLast(new ChannelDuplexHandler() {
                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                        IdleStateEvent event = (IdleStateEvent) evt;
                        if (event.state() == IdleState.READER_IDLE) {
                            log.info("客户端30s没有发送消息，自动断开连接");
                            ctx.channel().close();
                        }
                    }
                })
                .addLast(loggingHandler)
                .addLast(new ProtocolFrameDecoder())
                .addLast(new SharedMessageCodec())
                .addLast(new ForwardMessagesHandler());
    }

}
